package com.topway.dsmflex.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintStream;

import org.apache.log4j.Logger;
import org.eclipse.swt.custom.StyledText;

public class PrintLog extends Thread {

	private static Logger log = Logger.getLogger(PrintLog.class);
	
	
	private PipedInputStream pipedOutIn;
	private PipedInputStream pipedErrIn;

	private StyledText txtOutput;
	private static final int MAX_ROW = 200;

	public PrintLog(StyledText txtOutput) {
		this.txtOutput = txtOutput;
		pipedOutIn = new PipedInputStream();
		pipedErrIn = new PipedInputStream();
		try {
			System.setOut(new PrintStream(new PipedOutputStream(pipedOutIn),
					true));
			System.setErr(new PrintStream(new PipedOutputStream(pipedErrIn),
					true));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		BufferedReader systemOutIn = new BufferedReader(new InputStreamReader(
				pipedOutIn));
		BufferedReader systemErrIn = new BufferedReader(new InputStreamReader(
				pipedErrIn));
		int row = 0;
		while (true) {
			try {
				if (systemOutIn.ready()) {
					row++;
					if (row > MAX_ROW) {
						row = 0;
						txtOutput.setText("");
					}
					String text = systemOutIn.readLine();

					txtOutput.append("\n");
					txtOutput.append(text);
				}

				if (systemErrIn.ready()) {
					row++;
					if (row > MAX_ROW) {
						row = 0;
						txtOutput.setText("");
					}
					String text = systemErrIn.readLine();

					txtOutput.append("\n");
					txtOutput.append(text);
				}

			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
